package io.geekidea.boot.test.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.framework.page.OrderByItem;
import io.geekidea.boot.framework.page.OrderMapping;
import io.geekidea.boot.framework.page.Paging;
import io.geekidea.boot.test.dto.CarsDto;
import io.geekidea.boot.test.entity.Cars;
import io.geekidea.boot.test.mapper.CarsMapper;
import io.geekidea.boot.test.query.CarsQuery;
import io.geekidea.boot.test.service.CarsService;
import io.geekidea.boot.test.vo.CarsVo;
import io.geekidea.boot.test.query.AppCarsQuery;
import io.geekidea.boot.test.vo.AppCarsVo;
import io.geekidea.boot.util.PagingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * 车辆 服务实现类
 *
 * @author geekidea
 * @since 2025-03-26
 */
@Slf4j
@Service
public class CarsServiceImpl extends ServiceImpl<CarsMapper, Cars> implements CarsService {

    @Autowired
    private CarsMapper carsMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addCars(CarsDto dto) {
        Cars cars = new Cars();
        BeanUtils.copyProperties(dto, cars);
        return save(cars);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateCars(CarsDto dto) {
        Long id = dto.getId();
        Cars cars = getById(id);
        if (cars == null) {
            throw new BusinessException("车辆不存在");
        }
        BeanUtils.copyProperties(dto, cars);
        return updateById(cars);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteCars(Long id) {
        return removeById(id);
    }

    @Override
    public CarsVo getCarsById(Long id) {
        return carsMapper.getCarsById(id);
    }

    @Override
    public Paging<CarsVo> getCarsPage(CarsQuery query) {
        OrderMapping orderMapping = new OrderMapping();
        orderMapping.put("createTime", "create_time");
        PagingUtil.handlePage(query, orderMapping, OrderByItem.desc("id"));
        List<CarsVo> list = carsMapper.getCarsPage(query);
        Paging<CarsVo> paging = new Paging<>(list);
        return paging;
    }

    @Override
    public AppCarsVo getAppCarsById(Long id) {
        return carsMapper.getAppCarsById(id);
    }

    @Override
    public Paging<AppCarsVo> getAppCarsPage(AppCarsQuery query) {
        OrderMapping orderMapping = new OrderMapping();
        orderMapping.put("createTime", "create_time");
        PagingUtil.handlePage(query, orderMapping, OrderByItem.desc("id"));
        List<AppCarsVo> list = carsMapper.getAppCarsPage(query);
        Paging<AppCarsVo> paging = new Paging<>(list);
        return paging;
    }

}
